package com.ouc.ouc.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ouc.openplatform.ouc.userLogin.model.NJ_UserInfoDto;
import com.ouc.ouc.service.ClientUserLoginServiceAdapter;
import com.ouc.pampas.SessionSecurityConstants;
@Controller
public class LoginController {
	
	
	@Resource
	private ClientUserLoginServiceAdapter clientUserLoginServiceAdapter;
	
	@RequestMapping(value="/login",method = {RequestMethod.POST},produces = MediaType.TEXT_HTML_VALUE)
	@ResponseBody
	public void locallogin(HttpServletRequest request, HttpServletResponse response){
		
		String userCode = request.getParameter("loginname");
		String password = request.getParameter("password");

		//获取前一个链接地址，用以判断用户从哪里访问系统
		String regUrl = request.getHeader("Referer");
		NJ_UserInfoDto nj_UserInfo=new NJ_UserInfoDto();
		
		try {
			 nj_UserInfo = clientUserLoginServiceAdapter.mUserLogin(userCode,DigestUtils.md5DigestAsHex(password.getBytes()));
		} catch (Exception e) {
			nj_UserInfo=null;
		}
		
		if(nj_UserInfo==null){//登陆失败
			System.out.println("登录认证失败！");
			//不跳转并刷新页面
			try {
				Cookie errcookie = new Cookie("issuccess", "false");
				response.addCookie(errcookie);
				response.sendRedirect(regUrl);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} else{//登陆成功
			System.out.println("登录认证成功！");
			//只通过用户名从本系统数据表中获取用户信息
			String username = nj_UserInfo.getRealname();
			Long userid=(long) nj_UserInfo.getId();
			int roleid=nj_UserInfo.getRoleid();
			request.getSession().setAttribute(SessionSecurityConstants.KEY_CHECKCODE,roleid);
			request.getSession().setAttribute(SessionSecurityConstants.KEY_USER_NAME,username);
			request.getSession().setAttribute(SessionSecurityConstants.KEY_USER_NICK_NAME,username);
			request.getSession().setAttribute(SessionSecurityConstants.KEY_USER_ID,userid);
			try {
				// 获取值放入cookie
				//建立无生命周期的cookie，即随着浏览器的关闭即消失的cookie
				//登录名
	            Cookie cookie_userCode = new Cookie("loginname", userCode);
				response.addCookie(cookie_userCode);
				//用户角色ID
				Cookie cookie_roleid = new Cookie("roleid", Integer.toString(roleid));
				response.addCookie(cookie_roleid);
				
			    response.sendRedirect("/index");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(HttpServletRequest request){
		request.getSession().invalidate();
		return "redirect:/login";
	}

}
